package com.demonzym.framework.net.json;

import org.json.JSONException;
import org.json.JSONObject;


public class MyJSONObject {
	JSONObject mJsonObj;

	public MyJSONObject() {
		mJsonObj = new JSONObject();
	}
	
	public MyJSONObject(JSONObject jsonObj){
		mJsonObj = jsonObj;
	}
	
	public MyJSONObject(String json) throws MyJSONException {
		try {
			mJsonObj = new JSONObject(json);
		} catch (JSONException e) {
			throw new MyJSONException(e.getMessage());
		}
	}
//
//	public JSONObject getJsonObject(){
//		return mJsonObj;
//	}

	public String optString(String name) {
		if(mJsonObj	!= null){
			String str = mJsonObj.optString(name);
			if(str != null && str.equalsIgnoreCase("null"))
				return "";
			else
				return str;
		}
		return null;
	}

	public MyJSONArray optJSONArray(String name) {
		if(mJsonObj	!= null)
			return new MyJSONArray(mJsonObj.optJSONArray(name));
		
		return null;
	}

	public MyJSONObject optJSONObject(String name) {
		if(mJsonObj	!= null)
			return new MyJSONObject(mJsonObj.optJSONObject(name));
		
		return null;
	}

	public void put(String name, Object value) throws MyJSONException {
		if(mJsonObj != null){
			try {
				if(value instanceof MyJSONObject)
					mJsonObj.put(name, ((MyJSONObject)value).mJsonObj);
				else if(value instanceof MyJSONArray)
					mJsonObj.put(name, ((MyJSONArray)value).mJsonArry);
				else
					mJsonObj.put(name, value);
			} catch (JSONException e) {
				throw new MyJSONException(e.getMessage());
			}
		}
		else{
			throw new MyJSONException("not new mJsonObj");
		}
	}

	public int optInt(String name) {
		if(mJsonObj != null)
			return mJsonObj.optInt(name);
		
		return 0;
	}

	public boolean optBoolean(String name) {
		if(mJsonObj != null)
			return mJsonObj.optBoolean(name);
		return false;
	}

	public int optInt(String name, int fallback) {
		if(mJsonObj != null)
			return mJsonObj.optInt(name, fallback);
		return 0;
	}


	
	@Override
	public String toString() {
		if(mJsonObj != null)
			return mJsonObj.toString();
		
		return super.toString();
	}


}
